package com.atguigu.flink.timer;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.TimerService;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2023/4/10
 *
 *  监控传感器的水位值，如果水位值在5s之内(event time)连续上升，则报警
 *
 *      保存的变量:
 *          ①有定时器触发的时间(绝对时间)
 *          ②保存一个标记，表明当前已经制定过定时器了，
 *                  在这个定时器触发或删除之前，都没有必要再去制定新的定时器。
 *                  一旦定时器被触发或删除，需要更新这个标记，表明现在没有定时器了，下一条数据来
 *                  就需要制定定时器
 *         ③保存上一个传感器的水位，对比发现是上升还是下降
 *
 *     --------------------
 *      当前去验证时，一定只发一种key，否则会出现问题！
 *              后续学习了状态后，可以解决！
 *
 */
public class Demo3_TimerExec
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
            .<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner( (e, ts) -> e.getTs());

        KeyedStream<WaterSensor, String> ds = env
            .socketTextStream("hadoop102", 8888)
            .map(new WaterSensorMapFunction())
            .assignTimestampsAndWatermarks(watermarkStrategy)
            .keyBy(WaterSensor::getId);


        ds.process(new KeyedProcessFunction<String, WaterSensor, String>()
        {
            //时器触发的时间
            private long time ;
            //标记，表明当前已经制定过定时器了
            private boolean ifNeedToMakeTimer = true;
            //保存上一个传感器的水位
            private int lastVc ;


            //编写定时器执行的代码
            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {

                out.collect(ctx.getCurrentKey() + "在 "+timestamp +" 报警，连续5s水位上升....");

                //重置标记
                ifNeedToMakeTimer = true;

            }



            @Override
            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                TimerService timerService = ctx.timerService();

                if (ifNeedToMakeTimer){

                    time = ctx.timestamp() + 5000;
                    System.out.println(ctx.getCurrentKey() + "在" + time +" 注册了定时器...");
                    timerService.registerEventTimeTimer(time);
                    //更新标记
                    ifNeedToMakeTimer = false;
                }

                //单位是毫秒时间戳
                if (value.getVc() < lastVc){
                    timerService.deleteEventTimeTimer(time);
                    System.out.println(ctx.getCurrentKey() + "在" + time +" 删除了定时器...");
                    //重置标记
                    ifNeedToMakeTimer = true;
                }

                //记录当前传感器的水位，方便和后续的比较
                lastVc = value.getVc();

                out.collect(value.toString());
            }

        })
          .print();


        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
